package com.hernie.piggymall.member.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.hernie.common.utils.HttpUtils;
import com.hernie.piggymall.member.dao.MemberLevelDao;
import com.hernie.piggymall.member.entity.MemberLevelEntity;
import com.hernie.piggymall.member.exception.PhoneExistException;
import com.hernie.piggymall.member.exception.UsernameExistException;
import com.hernie.piggymall.member.vo.MemberLoginVo;
import com.hernie.piggymall.member.vo.MemberRegistVo;
import com.hernie.piggymall.member.vo.SocialUser;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.bouncycastle.jcajce.provider.keystore.BC;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hernie.common.utils.PageUtils;
import com.hernie.common.utils.Query;

import com.hernie.piggymall.member.dao.MemberDao;
import com.hernie.piggymall.member.entity.MemberEntity;
import com.hernie.piggymall.member.service.MemberService;


@Service("memberService")
public class MemberServiceImpl extends ServiceImpl<MemberDao, MemberEntity> implements MemberService {

    @Autowired
    private MemberLevelDao memberLevelDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MemberEntity> page = this.page(
                new Query<MemberEntity>().getPage(params),
                new QueryWrapper<MemberEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void regist(MemberRegistVo vo) {
        MemberEntity entity = new MemberEntity();
        // 设置会员等级
        MemberLevelEntity levelEntity = memberLevelDao.getDefaultLevel();
        entity.setLevelId(levelEntity.getId());

        // 检查用户名和手机号是否唯一 ,为了让controller能感知异常，可以使用异常机制
        checkPhoneUnique(vo.getPhone());
        checkUsernameUnique(vo.getUsername());
        entity.setMobile(vo.getPhone());
        entity.setUsername(vo.getUsername());

        // 密码加密存储
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        String encode = passwordEncoder.encode(vo.getPassword());
        entity.setPassword(encode);

        this.baseMapper.insert(entity);
    }

    @Override
    public void checkPhoneUnique(String phone) throws PhoneExistException {
        Long count = this.baseMapper.selectCount(Wrappers.<MemberEntity>lambdaQuery().eq(MemberEntity::getMobile, phone));
        if (count > 0) {
            throw new PhoneExistException();
        }
    }

    @Override
    public void checkUsernameUnique(String username) throws UsernameExistException {
        Long count = this.baseMapper.selectCount(new QueryWrapper<MemberEntity>().eq("username", username));
        if (count > 0) {
            throw new UsernameExistException();
        }
    }

    @Override
    public MemberEntity login(MemberLoginVo vo) {
        String loginacct = vo.getLoginacct();
        String password = vo.getPassword();
        // 去数据库查询
        MemberEntity entity = this.baseMapper.selectOne(Wrappers.<MemberEntity>lambdaQuery().eq(MemberEntity::getUsername, loginacct).or().eq(MemberEntity::getMobile, loginacct));
        if (entity == null) {
            // 登录失败
            return null;
        } else {
            // 获取到数据库的password
            String passwordDb = entity.getPassword();
            BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
            // 进行密码匹配
            boolean matches = passwordEncoder.matches(password, passwordDb);
            if (matches) {
                // 比对成功
                return entity;
            } else {
                // 登陆失败
                return null;
            }
        }

    }

    @Override
    public MemberEntity login(SocialUser socialUser) throws Exception {
        // 注册和登录合并逻辑
        String uid = socialUser.getUid();
        // 判断当前社交用户是否已经登陆过系统
        MemberEntity member = this.baseMapper.selectOne(Wrappers.<MemberEntity>lambdaQuery().eq(MemberEntity::getSocialUid, uid));
        if (member != null) {
            // 用户以及注册过了
            member.setAccessToken(socialUser.getAccess_token());
            member.setExpiresIn(socialUser.getExpires_in());

            this.baseMapper.updateById(member);

            return member;
        } else {
            // 没有查询到当前社交用户的记录，自动注册
            MemberEntity entity = new MemberEntity();
            try {
                // 查询当前社交用户的社交帐号信息（昵称，性别等）
                HashMap<String, String> query = new HashMap<>();
                query.put("access_token", socialUser.getAccess_token());
                query.put("uid", socialUser.getUid());
                HttpResponse response = HttpUtils.doGet("https://api.weibo.com", "/2/users/show.json", "get", new HashMap<String, String>(), query);
                if (response.getStatusLine().getStatusCode() == 200) {
                    // 查询成功
                    String json = EntityUtils.toString(response.getEntity());
                    JSONObject jsonObject = JSONObject.parseObject(json);
                    // 昵称
                    String name = jsonObject.getString("name");
                    // 性别
                    String gender = jsonObject.getString("gender");

                    entity.setUsername(name);
                    entity.setGender("m".equals(gender) ? 1 : 0);


                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            entity.setSocialUid(socialUser.getUid());
            entity.setAccessToken(socialUser.getAccess_token());
            entity.setExpiresIn(socialUser.getExpires_in());

            this.baseMapper.insert(entity);
            return entity;
        }
    }

}